﻿#include "video_device.h"
#include "listener.h"
#include "audio_device.h"
#include <string>

template<> std::set<Device::Video::Listener::Interface*>
        Base::Listener::Interface<Device::Video::Listener::Interface>::listener_ =
        std::set<Device::Video::Listener::Interface*>();;

using namespace xcast;

class VideoDeviceListener : public Base::Listener::Interface<Device::Video::Listener::Interface> {
public:
  static void OnAddCamera(const char* device_id, bool add) {
    for (auto it:listener_) {
      it->OnAddCamera(device_id, add);
    }
  }

  static void OnCameraUpdate(const char* device_id, int state) {
    for (auto it : listener_) {
      it->OnCameraUpdate(device_id, state);
    }
  }

  static void
  OnCameraPreview(const char* device_id, uint8_t* data, uint32_t data_size, uint32_t format,
                  uint32_t width, uint32_t height) {
    for (auto it:listener_) {
      it->OnCameraPreview(device_id, data, data_size, format, width, height);
    }
  }
};

namespace Device {
namespace Video {
namespace Listener {
void Add(Interface* listener) {
  VideoDeviceListener::Add(listener);
}

void Remove(Interface* listener) {
  VideoDeviceListener::Remove(listener);
}
}

namespace XcastEvent {
void OnAddCamera(const char* device_id, bool add) {
  VideoDeviceListener::OnAddCamera(device_id, add);
}
  
void OnCameraUpdate(const char* device_id, int state) {
  VideoDeviceListener::OnCameraUpdate(device_id, state);
}

void OnCameraPreview(const char* device_id, uint8_t* data, uint32_t data_size, uint32_t format,
                     uint32_t width, uint32_t height) {
  VideoDeviceListener::OnCameraPreview(device_id, data, data_size, format, width, height);
}
}

bool IsSelected(const char* device_id) {
  xcast_data camera_name = xcast_core::get_property(XC_CAMERA_DEFAULT);
  size_t size = camera_name.size();
  if (size == 0) {
    return false;
  }
  return 0 == strcmp(camera_name, device_id);
}

int Select(const char* device_id) {
  xcast_data camera_name(device_id);
  int ret = xcast_core::set_property(XC_CAMERA_DEFAULT, camera_name);
  xcast_data state = xcast_core::get_property(XC_STREAM_STATE, "wemeet-channel", "video-out");
  if (xc_stream_running == state.int32_val()) {
    xcast_core::set_property(XC_STREAM_CAPTURE, "wemeet-channel", "video-out", camera_name);
  }
  return ret;
}
  
const std::string GetSelectedCamera() {
  std::string camera_name = xcast_core::get_property(XC_CAMERA_DEFAULT).str_val();
  return camera_name;
}

int Preview(const char* device_id, bool on) {
  xcast_data camera_name = xcast_core::get_property(XC_CAMERA_DEFAULT);
  xcast_data param(on);
  int ret;
  if (device_id && strlen(device_id)) {
    ret = xcast_core::set_property(XC_CAMERA_PREVIEW, device_id, param);
  } else {
    ret = xcast_core::set_property(XC_CAMERA_PREVIEW, camera_name.str_val(), param);
  }
  return ret;
}
}
}
